﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Mondial2014.Models.Context;
using Mondial2014.Models.Gambling;
using Mondial2014.Models.Monitoring;
using Mondial2014.Utils.Extensions;

namespace Mondial2014.Controllers
{
    public class HomeController : Controller
    {
        private readonly Mondial2014DbContext m_Context = new Mondial2014DbContext();

        public class HomeIndexViewModel
        {
            public IEnumerable<Gambler> Gamblers { get; set; }
            public IEnumerable<string> Updates { get; set; }
        }

        public ActionResult Index()
        {
            var model = new HomeIndexViewModel
            {
                Gamblers = m_Context.Gamblers,
            };

            var updateList = new List<string>();
            var updates = m_Context.Updates.OrderByDescending(u => u.Date).Take(3).OrderBy(u => u.Date).ToArray();
            foreach (var update in updates)
            {
                if (update is FixtureResultUpdate)
                {
                    var fixtureResultUpdate = m_Context.GetFixtureResultUpdates().Single(u => u.Id == update.Id);
                    updateList.Add(string.Format("{0}   |   {1} - {2}     {4}:{3}",
                        fixtureResultUpdate.Date.AddHours(3).ToString("dd.M HH:mm"),
                        fixtureResultUpdate.Fixture.Team1.Name,
                        fixtureResultUpdate.Fixture.Team2.Name,
                        fixtureResultUpdate.Fixture.Team1Score,
                        fixtureResultUpdate.Fixture.Team2Score));
                }
                if (update is KnockoutUpdate)
                {
                    var knockoutUpdate = m_Context.GetKnockoutUpdates().Single(u => u.Id == update.Id);
                    if (knockoutUpdate.Stage.Level != (int) StageType.Winner)
                    {
                        updateList.Add(string.Format("{0}   |   {1} עלתה ל{2}",
                            knockoutUpdate.Date.AddHours(3).ToString("dd.M HH:mm"),
                            knockoutUpdate.Team.Name,
                            knockoutUpdate.Stage.Name));    
                    }
                    else
                    {
                        updateList.Add(string.Format("{0}   |   {1} זכתה במונדיאל",
                            knockoutUpdate.Date.AddHours(3).ToString("dd.M HH:mm"),
                            knockoutUpdate.Team.Name));
                    }
                }
            }
            model.Updates = updateList;

            return View(model);
        }
    }
}